﻿using System.Collections.Generic;
using Dorm.Helpers;
using Dorm.Maps;
using Dorm.QueryObject;

namespace Dorm.Services
{
    public class FindService
    {
        private DataAccess dataAccess;

        public FindService(DataAccess _dataAccess)
        {
            dataAccess = _dataAccess;
        }

        public List<T> Find<T>(Query<T> query)
        {
            bool useImplicitTransaction = dataAccess.HasValidTransaction == false;

            try
            {
                if (useImplicitTransaction)
                    dataAccess.BeginTransaction();

                var entityList = (List<T>)new DbToEntityMapper() { IncludeAlias = true }
                                          .Map(typeof(T), new List<T>(), dataAccess.ExecuteReader(query.ToString()));

                if (query.PropertiesToLoad != null)
                {
                    var entityMaps = MapLocator.GetMap<T>();

                    foreach (var listToLoad in query.PropertiesToLoad)
                    {
                        entityList = (List<T>)new LoadService(dataAccess) { EntityMaps = entityMaps }
                                                  .Load(listToLoad, entityList);
                    }
                }

                if (useImplicitTransaction)
                    dataAccess.CommitTransaction();

                return entityList;
            }
            catch
            {
                if (useImplicitTransaction)
                    dataAccess.RollbackTransaction();

                throw;
            }
        }
    }
}
